<?php
/**
 *
 */

class PGlobal
{
    private static  $instance;
    public function __construct()
    {

    }

    public function renderNewPhones()
    {
        $dienthoai = new DienThoai();
        $page = new Template(TEMPLATE_DIR . 'home-dienthoai-box.html');
        $page['title'] = 'Điện thoại mới';
        foreach ($dienthoai->getNewPhones() as $row) {
            $page['dienthoai-box-item'] .= $this->renderBoxPhone($row);
        }
        $dienthoai->disconnect();
        return $page->render();
    }

    public static function toVnd($val)
    {
        return number_format((float)$val * 1000, 0, '.', ',');
    }

    public function renderHotPhones()
    {
        $dienthoai = new DienThoai();
        $page = new Template(TEMPLATE_DIR . 'home-dienthoai-box.html');
        $page['title'] = 'Điện thoại bán chạy';
        foreach ($dienthoai->getHotPhones() as $row) {

            $page['dienthoai-box-item'] .= $this->renderBoxPhone($row);
        }
        $dienthoai->disconnect();
        return $page->render();
    }

    public function renderBoxPhone($row) {
        $item = new Template(TEMPLATE_DIR . 'home-dienthoai-box-item.html');
        $row['pprice'] = PGlobal::toVnd($row['pprice']);

        $item->setArray($row);
        $khuyenmai = $this->getKhuyenMai($row['pid']);
        if (count($khuyenmai) > 0) {
            $khuyenmai = $khuyenmai[0];
            $item['khuyenmai'] = 'on';
            if ($khuyenmai['hinhthuckm'] == '1') {
                $item['kmdetail'] = PGlobal::toVnd($khuyenmai['giatri']) . ' VNĐ';
            } elseif ($khuyenmai['hinhthuckm'] == '2') {
                $item['kmdetail'] = PGlobal::toVnd(round($khuyenmai['giatri'] * $khuyenmai['giadt']/100)) . ' VNĐ';
            } else {
                $item['kmdetail'] = 'quà tặng';
            }
        }
        if (!file_exists($item['pimgurl'])) {
            $item['pimgurl'] = DEFAULT_IMG;
        }
        return $item->render();
    }

    public function renderKhachHang()
    {
        // Kiểm tra khách hàng đã đăng nhập chưa
        //if (isset($_SESSION['uid']))
    }

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new PGlobal();
        }
        return self::$instance;
    }

    public static function getLayoutTemplate()
    {
        $page = new Template(TEMPLATE_DIR . 'home.html');
        $page->addCss('css/home.css');
        $page->addCss('css/khlogin.css');


        $page->addJs('jsc/jquery-1.7.1.min.js');
        $page->addJs('jsc/dialog.js');
        $page->addJs('jsc/kh.js');
        $page->addJs('jsc/buy.js');
        $page->addJs('jsc/global.js');
        $page->addJs('jsc/jquery.example.min.js');

        $page['slide-show'] = SlideShow::getAll();
        $hangsx = new HangSx();
        foreach ($hangsx->listAll() as $row) {
            $ht = new Template(TEMPLATE_DIR . 'hangsx-item.html');
            $ht->setArray($row);
            $page['hangsx'] .= $ht->render();

            $ohsx = new Template(TEMPLATE_DIR . '/option-hangsx-item.html');
            $ohsx->setArray($row);
            $page['option-hangsx-item'] .= $ohsx->render();
        }

        // Kiểm tra tình trạng đăng nhập của khách hàng
        $kh_shopcart = new Template(TEMPLATE_DIR . 'home-kh-shopcart.html');
        $kh = '';
        if (isset($_SESSION[SESSION_KH])) {
            $kh = new Template(TEMPLATE_DIR . 'khachhang-msg-logged.html');
            $kh['taikhoankh'] = $_SESSION[SESSION_KH];
        } else {
            $kh = new Template(TEMPLATE_DIR . 'khachhang-msg.html');

            $khLoginTemplate = new Template(TEMPLATE_DIR . 'kh-login.html');
            $page['extra'] = $khLoginTemplate->render();
        }


        $kh_shopcart['khachhang-msg'] = $kh->render();
        $kh_shopcart['home-kh-shopcart-item'] = self::getInstance()->renderShopCart();
        $page['kh-shopcart'] = $kh_shopcart->render();

        $hangsx->disconnect();

        return $page;
    }

    public static function getAdminLayoutTemplate()
    {
        if(!Admin::isLogged()) {
            header('location: admin-login.php');
        } else {
            $page = PGlobal::getLayoutTemplate();

            // Admin menu
            $pmenu = new Template(TEMPLATE_DIR . 'sb-box-admin.html');
            $pmenu['admin-user'] = Admin::getCurrentAdmin();
            $page['sb-admin'] = $pmenu->render();

            $page->addCss('css/admin-cpanel.css');
            $page->addJs('jsc/admin-cpanel.js');
            return $page;
        }
    }

    public function renderShopCart()
    {
        if (!isset($_SESSION[SESSION_SHOPCART])) {
            return '';
        }
        $data = '';
        $shopcart =& $_SESSION[SESSION_SHOPCART];
        foreach ($shopcart as $id => $val) {
            $item = new Template(TEMPLATE_DIR . 'home-kh-shopcart-item.html');
            $item['id'] = $id;
            $item['name'] = $val['name'];
            $item['quantity'] = $val['quantity'];
            $data .= $item->render();
        }
        return $data;
    }

    public function renderShopcartDetail()
    {
        $dienthoai = new DienThoai();
        $content = new Template(TEMPLATE_DIR . 'checkout.html');
        $stt = 0;
        $total = 0;
        foreach ($_SESSION[SESSION_SHOPCART] as $id => $phone) {
            $gia = $dienthoai->executeScalar('SELECT giadt FROM dienthoai WHERE madt=:madt', array('madt' => $id));
            $km = $this->getKhuyenMai($id);
            $item = new Template(TEMPLATE_DIR . 'checkout-phone-item.html');
            $item['id'] = $id;
            $item['sott'] = ++$stt;
            $item['tendt'] = $phone['name'];
            $item['giadt'] = PGlobal::toVnd($gia);
            $item['price'] = $gia;
            $item['solg'] = $phone['quantity'];
            $tonggt = 0;

            // Điền thông tin khuyến mãi
            if (count($km) > 0) {
                $km = $km[0];
                $item['loaikm'] = $km['hinhthuckm'];
                $item['dongiakm'] = $km['giatri'];

                // Khuyến mãi tiền mặt
                if ($km['hinhthuckm'] == '1') {
                    $item['sale'] = $km['giatri'];
                } elseif ($km['hinhthuckm'] == '2') {
                    $item['sale'] = round($km['giatri'] * $gia / 100);
                }

                $item['gtkm'] = $km['hinhthuckm'] == '3' ? 'Tặng quà' : PGlobal::toVnd($item['sale']);
                $item['extra'] = 'thanhtien giamgia';
            } else {
                $item['loaikm'] = 0;
                $item['dongiakm'] = 0;
                $item['gtkm'] = 0;
                $item['sale'] = 0;
            }
            $thanhtien = (int)$gia * (int)$item['solg'] - $item['sale'];
            $item['total'] = $thanhtien;
            $item['thanhtien'] = PGlobal::toVnd($thanhtien);
            $total += $thanhtien;
            $content['checkout-phone-item'] .= $item->render();
        }
        $content['tongtien'] = PGlobal::toVnd($total);

        $dienthoai->disconnect();
        return $content->render();
    }

    public function getKhuyenMai($id)
    {
        $dienthoai = new DienThoai();
        $sql = file_get_contents(DB_DIR . 'khuyenmai.sql');
        return $dienthoai->run($sql, array('madt' => $id));
    }

    public function clearShopcart()
    {
        if (isset($_SESSION[SESSION_SHOPCART])) {
            unset($_SESSION[SESSION_SHOPCART]);
        }
        return 1;
    }

    public function changeQuantityShopcart($params)
    {
        $shopcart =& $_SESSION[SESSION_SHOPCART];
        $shopcart[$params['id']]['quantity'] = $params['quantity'];
        return 1;
    }
    /**
     * Thêm một sản phẩm vào giỏ hàng
     * @param $id
     * @return int
     */
    public function shopcart_addItem($id)
    {
        // Nếu id chưa có trong giỏ hàng thì tạo mới
        if (!isset($_SESSION[SESSION_SHOPCART])) {
            $_SESSION[SESSION_SHOPCART] = array();
        }
        $shopcart =& $_SESSION[SESSION_SHOPCART];

        if (isset($shopcart[$id])) {
            $shopcart[$id]['quantity'] += 1;
            return json_encode(array(
                                    'id' => $id,
                                    'name' => $shopcart[$id]['name'],
                                    'html' => $shopcart[$id]['quantity']));
        } else {
            $dienthoai = new DienThoai();
            $name = $dienthoai->executeScalar('SELECT tendt FROM dienthoai WHERE madt=:madt',
                array('madt' => $id));
            $shopcart[$id]['name'] = $name;
            $shopcart[$id]['quantity'] = 1;

            $item = new Template(TEMPLATE_DIR . 'home-kh-shopcart-item.html');
            $item['id'] = $id;
            $item['name'] = $shopcart[$id]['name'];
            $item['quantity'] = $shopcart[$id]['quantity'];
            $html = $item->render();

            return json_encode(array(
                                    'id' => $id,
                                    'name' => $name,
                                    'html' => $html));

            $dienthoai->disconnect();
        }

    }

    public function shopcart_removeItem($id)
    {
        if (isset($_SESSION[SESSION_SHOPCART]) && isset($_SESSION[SESSION_SHOPCART][$id])) {
            unset($_SESSION[SESSION_SHOPCART][$id]);
            return 1;
        } else {
            return 0;
        }
    }

    public function renderDienthoaiKhuyenmai()
    {
        $dienthoai = new DienThoai();
        $query = file_get_contents(DB_DIR . 'khuyenmai.sql');
        $khuyenmai = $dienthoai->run($query, array('madt' => '%'));
        $content = new Template(TEMPLATE_DIR . 'home-dienthoai-box.html');

        $sql = 'SELECT madt AS pid, tendt AS pname, giadt AS pprice, hinhdt AS pimgurl FROM dienthoai WHERE madt=:madt';
        foreach ($khuyenmai as $row) {
            $phone = $dienthoai->run($sql, array('madt' => $row['madt']));
            $content['dienthoai-box-item'] .= $this->renderBoxPhone($phone[0]);
        }

        if (count($khuyenmai) == 0) {
            $content['dienthoai-box-item'] = '<strong>Không có điện thoại nào đang trong chương trình khuyến mãi!</strong>';
        }
        $content['title'] = 'Các điện thoại đang khuyến mãi';

        $dienthoai->disconnect();
        return $content->render();

    }

    public function requestLoginForm()
    {
        $page = new Template(TEMPLATE_DIR . 'kh-login.html');
        return $page->render();
    }

    public function requestKhRegisterForm()
    {
        $page = new Template(TEMPLATE_DIR . 'kh-register.html');
        return $page->render();
    }

    public function requestNewAddressInput()
    {
        $page = new Template(TEMPLATE_DIR . 'newAddressInput.html');
        return $page->render();
    }

    public function order()
    {
        $newid = $this->getNewDondathangId();

    }

    public function getNewDondathangId()
    {
        $db = new Database();
        $d = date('my');
        $maxId =  $db->executeScalar('SELECT MAX(maddh) FROM dondathang WHERE maddh LIKE :maddh', array('maddh' => "{$d}%"));
        $db->disconnect();
        if ($maxId == null) {
            return "{$d}001";
        } else {
            $maxId = substr($maxId, 4, 3);
            return $d . str_pad($maxId + 1, 3, '0', STR_PAD_LEFT);
        }
    }

    public function submitDondh($diachi)
    {
        $db = new Database();

        // Thêm đơn hàng vào database
        $madh = $this->getNewDondathangId();
        $makh = KhachHang::getMakh($_SESSION[SESSION_KH]);

        $db->run('INSERT INTO dondathang VALUES(:maddh, :manv, :makh, :diachi, NOW(), 0);',
            array('maddh' => $madh, 'manv' => 1, 'makh' => $makh, 'diachi' => $diachi));

        $shopcart =& $_SESSION[SESSION_SHOPCART];
        // Thêm chi tiết đơn đặt hàng
        foreach ($shopcart as $id => $item) {
            $gia = $db->executeScalar('SELECT giadt FROM dienthoai WHERE madt=:id', array('id' => $id));
            $bind = array('maddh' => $madh, 'madt' => $id, 'dongiadh' => $gia, 'solg' => $item['quantity']);

            $db->run('INSERT INTO chitietddh VALUES(:maddh, :madt, :dongiadh, :solg)', $bind);
        }

        // Release database connection
        $db->disconnect();

        $this->clearShopcart();

        return 1;
    }

    public function renderBanggia($id)
    {
        $dt = new DienThoai();
        $data = $dt->select('mahsx=:id', array('id' => $id));
        $html = '';
        $stt = 0;
        foreach ($data as $row) {
            $tpl = new Template(TEMPLATE_DIR . 'banggia-ketqua-item.html');
            $tpl->setArray($row);
            $tpl['stt'] = ++$stt;
            $tpl['giadt'] = self::toVnd($tpl['giadt']);
            $html .= $tpl->render();
        }

        $dt->disconnect();
        return $html;
    }

    public static function handlerUploadFile()
    {
        $newfile = $_POST['hinhdt'];
        // Upload file
        if (isset($_FILES['fhinhdt']) &&
            $_FILES['fhinhdt']['type'] ='image/jpeg' &&
            $_FILES['fhinhdt']['type'] ='image/gif' &&
            $_FILES['fhinhdt']['type'] ='image/pjpeg') {
            $filename = $_FILES['fhinhdt']['name'];
            $it = explode(".", $filename);
            $ext = '.' . end($it);
            $filename = substr($filename, 0, strlen($filename) - strlen($ext));
            $base = 'anhdt2/';
            $newfile = $base . $filename . $ext;
            $stt = 0;
            while (file_exists($newfile)) {
                $newfile = $base . $filename . ++$stt . $ext;
            }

            move_uploaded_file($_FILES['fhinhdt']['tmp_name'], $newfile);
        }
        return $newfile;
    }

    public function getPhonePagination($params = '')
    {
        $bind = array();
        $pag = '';
        $dienthoai = '';

        if (isset($params['keyword'])) {
            $bind = array('madt' => $params['keyword']);
            $_SESSION['keyword'] = $params['keyword'];
        } elseif (isset($_SESSION['keyword'])) {
            $bind = array('madt' => $_SESSION['keyword']);
        } else {
            $bind = array('madt' => '%');
        }
        $db = new Database();


        $start = 0;
        if (isset($params['page'])) {
            $start = ($params['page'] - 1) * RECORD_PER_PAGE;
        } else {
            $params['page'] = 1;
        }

        $sql = 'SELECT madt, tendt, giadt FROM dienthoai WHERE CONVERT(madt USING utf8) LIKE :madt OR CONVERT(tendt USING utf8) LIKE :madt';
        $sql .= ' LIMIT ' . $start . ',' . RECORD_PER_PAGE;
        $data = $db->run($sql, $bind);


        $stt = $start;

        foreach ($data as $row) {
            $item = new Template(TEMPLATE_DIR . 'admin-dienthoai-item.html');
            $item->setArray($row);
            $item['stt'] = ++$stt;
            $item['giadt'] = self::toVnd($item['giadt']);
            $dienthoai .= $item->render();
        }

        $csql = 'SELECT count(*) FROM dienthoai WHERE CONVERT(madt USING utf8) LIKE :madt OR CONVERT(tendt USING utf8) LIKE :madt';
        $count = $db->executeScalar($csql, $bind);

        $count = ceil($count / RECORD_PER_PAGE);

        for ($i = 1; $i <= $count; $i++) {
            $item = new Template(TEMPLATE_DIR . 'admin-dienthoai-pagination.html');
            $item['number'] = $i;
            if ($params['page'] == $i) {
                $item['extra'] = 'selected';
            }

            $pag .= $item->render();
        }


        $db->disconnect();

        return json_encode(array('data' => $dienthoai, 'paging' => $pag));
    }
}
